<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 给你一个链表，每k个节点一组进行翻转，请你返回翻转后的链表。

        // 给定这个链表：1 -> 2 -> 3 -> 4 -> 5
        // 当 k = 2 时，应当返回: 2 -> 1 -> 4 -> 3 -> 5
        // 当 k = 3 时，应当返回: 3 -> 2 -> 1 -> 4 -> 5
        function reverseKGroup(head, k) {
            var stack = [], dummy = { next: null };
            let pre = dummy;
            while (true) {
                let count = 0, tmp = head;
                while (tmp && count < k) {
                    stack.push(tmp);
                    tmp = tmp.next;
                    count++;
                }
                if (count != k) {
                    pre = pre.next;
                    break;
                }
                while (stack.length > 0) {
                    pre.next = stack.pop();
                    pre = pre.next;
                }
                pre.next = tmp;
                head = tmp;
            }
            return dummy.next;
        };

        // 第二遍
        function reverseGroup(head, k) {

            var stack = [];
            var dummy = {
                next = null
            }
            var pre = dummy;
            var tmp = head;
            while (true) {
                // k个 一组
                var count = 0;

                // 从head 开始, 从0 开始 ,注意 ... 
                // 截止时,tmp 是 k+1位置
                while (tmp && count < k) {
                    stack.push(tmp);
                    tmp = tmp.next;
                }

                // 跳出条件
                if(count!=k){
                    break;
                }

                // 拼接链表
                while (stack.length > 0) {
                    pre.next = stack.pop();
                    pre = pre.next;
                }
                pre.next = tmp;
                count = 0;
            }
            return dummy.next;
        }

    </script>
</body>

</html>